<!-- 优惠券管理 -->
<template>
  <div>
    <el-header>
      <el-space wrap>
        <el-input
          style="width: 190px"
          v-model.trim="configReq.title"
          clearable
          placeholder="请输入优惠券标题"
        />
        <el-select
          v-model="configReq.type"
          clearable
          placeholder="请选择优惠券类型"
        >
          <el-option
            v-for="item in options.type"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="configReq.status"
          clearable
          placeholder="请选择优惠券状态"
        >
          <el-option
            v-for="item in options.status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" :icon="Search" @click="debounce(getInfo)"
          >查找</el-button
        >
        <el-button
          type="primary"
          :icon="Plus"
          @click="
            () => {
              resetAddData();
              disabled = false;
              title = '创建';
              dialogShow = true;
            }
          "
          v-btn="'promotion:coupon:create'"
          >添加</el-button
        >
        <el-button
          type="primary"
          :icon="Download"
          @click="exportExcel('#exportTab')"
          >当前页导出</el-button
        >
      </el-space>
    </el-header>
    <el-container>
      <!-- 列表 -->
      <el-table id="exportTab" :data="infoList" border align="center">
        <el-table-column prop="id" label="优惠券ID" align="center" width="90" />
        <el-table-column prop="title" label="优惠券名称" align="center" />
        <el-table-column label="优惠券类型" align="center" width="100">
          <template #default="scope">
            <el-tag>{{ scope.row.type == 1 ? "满减券" : "立减券" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="description"
          label="介绍"
          width="120"
          align="center"
        />
        <el-table-column prop="total" label="优惠券数量" align="center" />
        <el-table-column prop="surplus" label="剩余数量" align="center" />
        <el-table-column prop="limit" label="每人限领" align="center" />
        <el-table-column label="满减金额" align="center" width="100">
          <template #default="scope"> 减免{{ scope.row.discount }}元 </template>
        </el-table-column>
        <el-table-column label="最低消费" align="center" width="130">
          <template #default="scope"> 满{{ scope.row.min }}元可用 </template>
        </el-table-column>
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status == 1 ? '' : 'danger'">{{
              switchDetails(scope.row.status)
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="使用类目名称" align="center" width="110">
          <template #default="scope">
            <el-tag>{{
              scope.row.categoryTitle ? scope.row.categoryTitle : "全部类目"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="categoryId" label="使用类目ID" align="center" />
        <el-table-column label="领券相对天数" align="center">
          <template #default="scope">
            {{ scope.row.days ? scope.row.days : "无" }}
          </template>
        </el-table-column>
        <el-table-column label="领券开始时间" align="center">
          <template #default="scope">
            {{ computTime(scope.row.gmtStart) }}
          </template>
        </el-table-column>
        <el-table-column label="领券结束时间" align="center">
          <template #default="scope">
            {{ computTime(scope.row.gmtEnd) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="操作" align="center" width="200">
          <template #default="scope">
            <el-button
              type="primary"
              @click="debounce(changeStatus, scope.row)"
              >{{ switchHandle(scope.row.status) }}</el-button
            >
            <el-button type="info" @click="lookInfo(scope.row)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹出框 -->
      <el-dialog
        v-model="dialogShow"
        :title="title"
        width="750px"
        destroy-on-close
      >
        <el-form
          ref="formRef"
          :disabled="disabled"
          :model="addData"
          :rules="rules"
          label-width="120px"
          status-icon
        >
          <el-form-item label="优惠券名称" prop="title">
            <el-input v-model.trim="addData.title" type="text" />
          </el-form-item>
          <el-form-item label="优惠券类型" prop="type">
            <el-select v-model="addData.type" placeholder="请选择优惠券类型">
              <el-option
                v-for="item in options.type.slice(0, 2)"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="介绍" prop="description">
            <el-input v-model="addData.description" type="text" />
          </el-form-item>
          <el-form-item label="优惠券数量" prop="total">
            <el-input
              v-model="addData.total"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="7"
            >
              <template #append>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="每人限领" prop="limit">
            <el-input
              v-model="addData.limit"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="7"
            >
              <template #append>张</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠金额" prop="discount">
            <el-input
              v-model="addData.discount"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="7"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="最低消费" prop="min">
            <el-input
              v-model="addData.min"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="7"
            >
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="优惠券状态" prop="status">
            <el-select v-model="addData.status" placeholder="请选择优惠券状态">
              <el-option
                v-for="item in options.status.slice(
                  0,
                  addData.status == -1 ? 3 : 2
                )"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="有效期">
            <el-radio-group v-model="radio.indate" style="margin-bottom: 20px">
              <el-radio-button label="0">领券相对天数</el-radio-button>
              <el-radio-button label="1">指定绝对时间</el-radio-button>
            </el-radio-group>
            <el-input
              v-if="radio.indate == 0"
              v-model="addData.days"
              type="text"
              oninput="value=value.replace(/[^\d]/g,'')"
              maxlength="5"
            >
              <template #append>天</template>
            </el-input>
            <div v-if="radio.indate == 1">
              <el-date-picker
                v-model="addData.gmtStart"
                type="datetime"
                placeholder="选择日期"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="x"
              />
              <span style="margin: 0px 1rem">至</span>
              <el-date-picker
                v-model="addData.gmtEnd"
                type="datetime"
                placeholder="选择日期"
                format="YYYY/MM/DD hh:mm:ss"
                value-format="x"
              />
            </div>
          </el-form-item>
          <el-form-item label="商品限制范围">
            <el-radio-group v-model="radio.scope">
              <el-radio-button label="0">全场通用</el-radio-button>
              <el-radio-button label="1">指定分类</el-radio-button>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="优惠类目" v-if="radio.scope == 1">
            <el-cascader
              v-model="addData.categoryId"
              :props="props"
              placeholder="优惠类目"
              :options="categorytList"
              :show-all-levels="false"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span>
            <el-button @click="dialogShow = false">取消</el-button>
            <el-button
              type="primary"
              @click="submitForm('formRef')"
              v-if="!disabled"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-container>
    <el-footer>
      <!-- 分页组件 -->
      <paging v-bind="pageInfo" @changeReq="changeConfig"></paging>
    </el-footer>
  </div>
</template>

<script>
import { post } from "@/utils/http";
import { Search, Plus, Download } from "@element-plus/icons-vue";
import Paging from "@/components/paging/Paging";
import { exportExcel } from "@/table";

export default {
  setup() {
    return {
      Search,
      Plus,
      Download,
      exportExcel,
    };
  },
  components: { Paging },
  data() {
    return {
      infoList: [], //数据列表
      categorytList: [], //类目列表
      title: "", //弹出框title
      disabled: false, //弹出框表单是否禁用
      dialogShow: false, // 是否显示弹出框
      // 请求表格数据的配置
      configReq: {
        _gp: "admin.coupon",
        _mt: "list",
        title: "", //优惠卷标题
        type: null, //优惠券类型
        status: null, //优惠券状态
      },
      // 传给分页组件的数据
      pageInfo: {
        page: 1, //跳转页数
        limit: 10, //显示条数
        total: 0,
      },
      // 优惠券的选择器数据
      options: {
        type: [
          { value: 1, label: "满减券" },
          { value: 2, label: "立减券" },
          { value: "", label: "全部" },
        ],
        status: [
          { value: 0, label: "下架" },
          { value: 1, label: "正常" },
          { value: -1, label: "已过期" },
          { value: "", label: "全部" },
        ],
      },
      // 添加时传递的数据
      addData: {
        _gp: "admin.coupon",
        _mt: "create",
        title: "", //标题
        type: 1, //类型
        description: "", //描述
        total: 0, //总数
        limit: 0, //限制领取
        discount: 0, //优惠价格
        min: 0, //满足优惠的最低价格
        status: 1, //状态
        categoryId: "", //优惠类别
        days: null, //优惠时长
        gmtStart: null, //开始时间
        gmtEnd: null, //结束时间
      },
      // 验证规则
      rules: {
        title: [
          { message: "优惠券名称不能为空", trigger: "blur", required: true },
        ],
        type: [{ required: true }],
        description: [{ required: false }],
        total: [
          { message: "优惠券数量不能为空", trigger: "blur", required: true },
        ],
        limit: [
          { message: "请输入每人限领的数量", trigger: "blur", required: true },
        ],
        discount: [
          { message: "优惠金额不能为空", trigger: "blur", required: true },
        ],
        min: [
          { message: "最低消费金额不能为空", trigger: "blur", required: true },
        ],
        status: [{ required: true }],
      },
      // 单选按钮
      radio: { indate: 0, scope: 0 },
      // 类目级联选择器的配置
      props: {
        label: "title",
        children: "childrenList",
        value: "id",
        emitPath: false,
        checkStrictly: true,
      },
    };
  },
  methods: {
    // 获取类目数据的方法
    getCategoryt() {
      post({ _gp: "admin.category", _mt: "categoryTree" }).then((res) => {
        if (200 == res.errno) {
          //成功状态码
          // console.log(res.data);
          this.categorytList = res.data;
        }
      });
    },
    // 判断状态的函数
    switchStatus(row) {
      let now = new Date().getTime(); //获取当前时间的时间戳
      //过期时
      if (row.gmtEnd < now) return -1;
      //错误时
      if (row.status == 2) return 2;
      return row.status ? 1 : 0;
    },
    // 获取表格数据的方法
    getInfo() {
      post(this.configReq)
        .then((res) => {
          if (200 == res.errno) {
            //成功状态码
            // console.log(res.data)
            const data = res.data;
            this.infoList = data.items; //获取表格信息
            //判断状态
            for (const row of this.infoList) {
              row.status = this.switchStatus(row);
            }
            this.pageInfo.total = data.total; //获取总条数
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 组件触发的数据改变
    changeConfig(data) {
      let { page: pageNo, limit } = data;
      Object.assign(this.configReq, { pageNo, limit });
      this.getInfo();
    },
    //状态标签显示的内容
    switchDetails(status) {
      switch (status) {
        case 1:
          return "正常";
        case 0:
          return "下架";
        case -1:
          return "已过期";
      }
    },
    // 操作按钮的名字
    switchHandle(status) {
      switch (status) {
        case 1:
          return "冻结";
        case 0:
          return "激活";
        case -1:
          return "已过期";
      }
    },
    //计算时间
    computTime(time) {
      let { year, month, date, hour, minute } = new Date(time).formatDate();
      let arr = [year, month, date];
      let data = time ? arr.join("-") + " " + hour + ":" + minute : "无";
      return data;
    },
    // 重置数据
    resetAddData() {
      this.addData = {
        _gp: "admin.coupon",
        _mt: "create",
        title: "",
        type: 1,
        description: "",
        total: 0,
        limit: 0,
        discount: 0,
        min: 0,
        status: 1,
        categoryId: "",
        days: null,
        gmtStart: null,
        gmtEnd: null,
      };
    },
    // 改变状态
    changeStatus(row) {
      let config = {
        _gp: "admin.coupon",
        _mt: "updateCouponStatus",
        id: row.id,
        status: 1,
      };
      switch (row.status) {
        case 1:
          config.status = 0;
          break;
        case 0:
          config.status = 1;
          break;
        case -1:
          ElMessage.error("过期优惠券，建议删除");
          return;
      }
      post(config)
        .then((res) => {
          if (200 == res.errno) {
            ElMessage.success("操作成功");
            this.getInfo();
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    // 提交添加数据
    submitForm(formEl) {
      this.$refs[formEl].validate((valid) => {
        if (valid) {
          let data = this.addData;
          this.radio.indate == 1
            ? data.days == null
            : ((data.gmtStart = null), (data.gmtEnd = null)); //时间的判断
          data.categoryId = this.radio.scope == 1 ? data.categoryId : ""; //给类目进行判断
          post(data).then((res) => {
            if (200 == res.errno) {
              ElMessage.success("添加成功");
              this.dialogShow = false; //关闭弹窗
              this.getInfo(); //刷新数据
            }
          });
        }
      });
    },
    lookInfo(row) {
      this.resetAddData();
      Object.assign(this.addData, row);
      this.disabled = true;
      this.title = "编辑";
      this.radio.indate = this.addData.days ? 0 : 1;
      this.radio.scope = this.addData.categoryId ? 1 : 0;
      this.dialogShow = true;
    },
  },
  created() {
    this.getInfo();
  },
  watch: {
    //弹出框是否显示
    dialogShow(n) {
      if (this.categorytList.length != 0) return; //长度不为0时获取树
      if (n) this.getCategoryt();
    },
  },
};
</script>

<style scoped lang="less">
.el-header {
  height: auto;
  margin-bottom: 20px;
}
</style>
